<template>
	<view class="container">
		<view class="form-item">
			<input v-model="formData.title" placeholder="请输入标题" class="input" />
		</view>

		<view class="form-item">
			<textarea maxlength="-1" v-model="formData.content" placeholder="请输入内容" class="textarea" auto-height />
		</view>

		<button type="primary" class="submit-btn" @click="handleSubmit">提交</button>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { createPost } from '../../api/community.js';

const formData = ref({
	title: '',
	content: ''
});

const userInfo = JSON.parse(uni.getStorageSync('user_info') || '{}');

const handleSubmit = async () => {
	if (!formData.value.title.trim()) {
		uni.showToast({ title: '标题不能为空', icon: 'none' });
		return;
	}

	if (!formData.value.content.trim()) {
		uni.showToast({ title: '内容不能为空', icon: 'none' });
		return;
	}

	try {
		uni.showLoading({ title: '提交中...', mask: true });

		const res = await createPost({
			title: formData.value.title,
			content: formData.value.content,
			userId: userInfo.id
		});
		uni.showToast({ title: '创建成功' });
		setTimeout(() => uni.navigateBack(), 1500);
	} catch (error) {
		uni.showModal({
			title: '提示',
			content: error.message || '请求失败，请检查网络',
			showCancel: false
		});
	} finally {
		uni.hideLoading();
	}
};
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
}

.form-item {
	margin-bottom: 30rpx;

	.label {
		display: block;
		font-size: 30rpx;
		margin-bottom: 10rpx;
		color: #333;
	}

	.input {
		height: 80rpx;
		padding: 0 20rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
	}

	.textarea {
		width: 100%;
		min-height: 200rpx;
		padding: 20rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
	}
}

.submit-btn {
	margin-top: 50rpx;
}
</style>
